package simtools.xml.test;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class RouterXML {
	
	private static Element  _xmlContent;
	private Document _doc;
	private String   _linkSpeed;
	private String   _delay;
	private String   _queue;
	
	
    public RouterXML() {
		
	}
    
	public RouterXML(Document doc) {
		this._doc = doc;
		
		processXML();
	}
	
	public RouterXML(Document doc, String linkSpeed, String delay, String queue) {
		this._linkSpeed  = linkSpeed;
		this._delay      = delay;
		this._queue      = queue;
		this._doc        = doc;
		
		processXML();
	}
	
	@SuppressWarnings("unchecked")
	public void processXML() {
		Element root = _doc.getRootElement();
		List<Element> links   = root.getChildren("Link");
		Iterator<Element> i   = links.iterator();

		Element newContent = new Element("Links");

		while (i.hasNext()) {
			Element link           = i.next();

			Element tempContent    = (Element) link.clone();

			if (_linkSpeed != null )
				tempContent.getChild("LinkSpeed").setText(_linkSpeed); 
			
			if (_delay != null)
				tempContent.getChild("Delay").setText(_delay);
			
			if (_queue != null)
				tempContent.getChild("Queue").setText(_queue);

			newContent.addContent(tempContent);
		}

		setXmlContent(newContent);
	}
	
	public void mostrarDados(Element content) {
		try {
			Format format = Format.getPrettyFormat();
            format.setLineSeparator("\n");
            
			XMLOutputter out = new XMLOutputter(format);
			out.output(content, System.out);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		
		String file = "xml/Routers.xml";
		
		try {
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(new File(file));
			
			RouterXML routerXML = new RouterXML(doc, "1000", null, null);
			//routerXML.processXML();
			routerXML.mostrarDados(getXmlContent());
	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setXmlContent(Element _xmlContent) {
		RouterXML._xmlContent = _xmlContent;
	}

	public static Element getXmlContent() {
		return _xmlContent;
	}

}
